package com.example.controller;

import com.example.common.Result;
import com.example.entity.Room;
import com.example.service.RoomService;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;

@RestController
@RequestMapping("/room")
@CrossOrigin(origins = "http://localhost:5173", allowCredentials = "true")
public class RoomController {
    private final RoomService roomService;

    public RoomController(RoomService roomService) {
        this.roomService = roomService;
    }

    @GetMapping
    public Result<List<Room>> getAllRooms() {
        return Result.success(roomService.getAllRooms());
    }

    @DeleteMapping("/{id}")
    public Result<Void> deleteRoom(@PathVariable Integer id) {
        if (roomService.deleteRoom(id)) {
            return Result.success(null);
        }
        return Result.error("删除失败");
    }

    @PostMapping
    public Result<List<Room>> addRoom(@RequestBody Room room) {
        // 验证必要参数
        if (room.getRoomName() == null || room.getRoomName().trim().isEmpty()) {
            return Result.error("房间名称不能为空");
        }
        if (room.getFamilyId() == null) {
            return Result.error("所属家庭ID不能为空");
        }
        
        // 检查是否已存在相同名称的房间
        Room existingRoom = roomService.getRoomByFamilyIdAndName(room.getFamilyId(), room.getRoomName());
        if (existingRoom != null) {
            return Result.error("该家庭已存在同名房间");
        }
        
        if (roomService.addRoom(room)) {
            // 查询新增的房间信息
            Room newRoom = roomService.getRoomById(room.getRoomId());
            return Result.success(Collections.singletonList(newRoom));
        }
        return Result.error("添加失败");
    }

    @GetMapping("/{id}")
    public Result<Room> getRoomById(@PathVariable Integer id) {
        Room room = roomService.getRoomById(id);
        if (room != null) {
            return Result.success(room);
        }
        return Result.error("未找到该房间");
    }

    @PutMapping
    public Result<Void> updateRoom(@RequestBody Room room) {
        try {
            // 验证必要参数
            if (room.getRoomId() == null) {
                return Result.error("房间ID不能为空");
            }
            if (room.getRoomName() == null || room.getRoomName().trim().isEmpty()) {
                return Result.error("房间名称不能为空");
            }
            
            // 获取原有房间信息
            Room existingRoom = roomService.getRoomById(room.getRoomId());
            if (existingRoom == null) {
                return Result.error("房间不存在");
            }
            
            // 检查是否重名（同一家庭下）
            Room sameNameRoom = roomService.getRoomByFamilyIdAndName(
                existingRoom.getFamilyId(), 
                room.getRoomName()
            );
            if (sameNameRoom != null && !sameNameRoom.getRoomId().equals(room.getRoomId())) {
                return Result.error("该家庭已存在同名房间");
            }

            // 设置不可修改的字段
            room.setFamilyId(existingRoom.getFamilyId());
            
            if (roomService.updateRoom(room)) {
                return Result.success(null);
            }
            return Result.error("更新失败");
        } catch (Exception e) {
            return Result.error("更新失败：" + e.getMessage());
        }
    }

    @GetMapping("/family/{familyId}")
    public Result<List<Room>> getRoomsByFamilyId(@PathVariable Integer familyId) {
        List<Room> rooms = roomService.getRoomsByFamilyId(familyId);
        if (rooms != null && !rooms.isEmpty()) {
            return Result.success(rooms);
        }
        return Result.error("未找到该家庭的房间");
    }
} 